<?php
/*
 * @Description    : 通用
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-04-17 09:01:53
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-04-28 17:00:09
 */

namespace app\api\controller;

use app\common\model\Manager;
use app\common\service\AliOss;
use app\common\Verify;
use app\lib\Result;
use think\facade\Request;
use Yurun\Util\HttpRequest;
use think\facade\Db;

class Common extends Base
{
  public static function sendEmail($postData)
  {
    $apiUrl = 'http://21ds.cn/email/send';
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['es_id'] = 'ES-4817058244179833';
    $postData['sign'] = devSignGeneral($postData, 'YS8mdSWn45ktxd3a6P6mef4wnWCRERFMdD8sdBz2iiNbPYbjpKFKrbijYSaYjeYt');
    $http = new HttpRequest;
    $http->post($apiUrl, $postData);
  }
  public static function sendSms($postData)
  {
    $apiUrl = 'http://21ds.cn/sms/send';
    $postData['dev_key'] = 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
    $postData['ss_id'] = 'SS-4820226106006849';
    $postData['sign'] = devSignGeneral($postData, 'YS8mdSWn45ktxd3a6P6mef4wnWCRERFMdD8sdBz2iiNbPYbjpKFKrbijYSaYjeYt');
    $http = new HttpRequest;
    $http->post($apiUrl, $postData);
  }
  public function uploadToWeixin()
  {
    if (request()->isPost()) {
      $files = request()->file();
      $mw_id = input('param.mw_id');
      $type = input('param.type');
      $title = input('param.title');
      $info = validate(['image' => 'filesize:10240|fileExt:jpg,png,gif,jpeg,bmp,mp4,mp3,wma,wav,amr'])->check($files);
      if ($info) {
        $http = new HttpRequest;
        foreach ($files as $file) {
          $saveFile = \think\facade\Filesystem::disk('wxtemp')->putFile('wxtemp', $file);
          $access_token = getWxAccessToken($mw_id,$this->uid);
          $wxUrlPj = '';
          if ($type == 'video') {
            $video['title'] = $title;
            $video['introduction'] = $title;
            $wxUrlPj = '&description=' . urlencode(json_encode($video));
          }
          $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=' . $access_token . '&type=' . $type . $wxUrlPj;
          $file_path = UPLOAD_PATH . $saveFile;
          $output = $this->wechatCurl($url, $file_path, $file->getOriginalName());
          if (!isset($output['media_id']) || empty($output['media_id'])) {
            return Result::Error('[' . $output['errcode'] . ']' . $output['errmsg']);
          }
          if ($type == 'image') {
            $mediaData['_id'] = createId();
            $mediaData['media_id'] = $output['media_id'];
            $mediaData['type'] = $type;
            $mediaData['url'] = isset($output['url']) ? $output['url'] : '';
            $mediaData['mw_id'] = $mw_id;
            $mediaData['uid'] = $this->uid;
            $mediaData['username'] = $this->username;
            $mediaData['create_time'] = time();
            Db::connect('mongodb')->name('wechat_media')->insert($mediaData);
          }
          return Result::Success(['media_id' => $output['media_id'], 'url' => $mediaData['url']]);
        }
        echo 'end';
      } else {
        var_dump($info);
        var_dump($files);
      }
    }
  }
  public function wechatCurl($url, $file_path, $file_name = '')
  {
    $file_data = array("media"  => new \CURLFile($file_path, null, $file_name));
    $ch = curl_init();
    //初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。
    curl_setopt($ch, CURLOPT_URL, $url);
    //需要获取的URL地址，也可以在curl_init()函数中设置。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //使用PHP curl获取页面内容或提交数据，有时候希望返回的内容作为变量储存，
    //而不是直接输出。这个时候就必需设置curl的CURLOPT_RETURNTRANSFER选项为1或true
    curl_setopt($ch, CURLOPT_POST, 1);
    //发送一个POST请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $file_data);
    //传递一个关联数组，生成multipart/form-data的POST请求
    $output = curl_exec($ch); //发送请求获取结果
    curl_close($ch);
    return json_decode($output, true);
  }
  public static function deleteFiles($url,$uid)
  {
    $parseUrl = parse_url($url);
    @unlink(PUBLIC_PATH . $parseUrl['path']);
    deleteFile('','FS-4829002155550872', $uid, null, $url);
  }
  public static function deleteAdsFiles($url)
  {
    $parseUrl = parse_url($url);
    if (stripos($parseUrl['host'], 'aliyuncs.com') != false) {
      # 在OSS上删除
      $ossClass = new AliOss();
      return $ossClass->deleteOssFile(ltrim($parseUrl['path'], '/'));
    }else if (stripos($parseUrl['host'], 'alicdn.com') != false) {
      return true;
    } else {
      return unlink(PUBLIC_PATH . $parseUrl['path']);
    }
  }
  public function upload()
  {
    header('Content-Type:application/json; charset=utf-8');
    if (request()->isPost()) {
      $file = request()->file();
      $type = input('param.type');
      $info = validate(['image' => 'filesize:30720|fileExt:jpg,png,gif,jpeg,bmp,doc,docx,xls,xlsx,ppt,pptx,zip,rar,txt,mp4,avi,flv'])->check($file);
      if ($info) {
        //基于框架根目录的文件路径
        $savename = [];
        foreach ($file as $ins) {
          $item['url'] = \think\facade\Filesystem::disk('public')->putFile('topic', $ins);
          $item['name'] = $ins->getOriginalName();
          $savename[] = $item;
        }
        $ossFileUrls = [];
        foreach ($savename as $sfile) {
          $sfile['url'] = str_replace('\\', '/', $sfile['url']);
          $fileD = new \Yurun\Util\YurunHttp\Http\Psr7\UploadedFile($sfile['name'], null, UPLOAD_PATH . $sfile['url']);
          $file_hash = md5_file(UPLOAD_PATH . $sfile['url']);
          $uploadResult = doFileUpload($fileD, 'FS-4829002155550872', 'FC-4830465021604083',null, $file_hash, $this->setting['dev_key']);
          if ($uploadResult['code'] == 200) {
            $ossFileUrls[] = $uploadResult['data']['url'];
          }
          unlink(UPLOAD_PATH . $sfile['url']);
        }
        if ($type == 'wangeditor') {
          $return['errno'] = 0;
          $return['data'] = [];
          foreach ($ossFileUrls as $file) {
            $return['data'][] = ['url' => $file];
          }
        } else {
          $return['code'] = 200;
          $return['data'] = $ossFileUrls;
        }
        return json($return);
      } else {
        var_dump($info);
        var_dump($file);
      }
    }
  }
  public function uploadFile()
  {
    header('Content-Type:application/json; charset=utf-8');
    if (request()->isPost()) {
      $file = request()->file();
      $type = input('param.type');
      $info = validate(['image' => 'filesize:30720|fileExt:jpg,png,gif,jpeg,bmp,doc,docx,xls,xlsx,ppt,pptx,zip,rar,txt,mp4,avi,flv'])->check($file);
      if ($info) {
        //基于框架根目录的文件路径
        $savename = [];
        foreach ($file as $ins) {
          $item['url'] = \think\facade\Filesystem::disk('public')->putFile('topic', $ins);
          $item['name'] = $ins->getOriginalName();
          $savename[] = $item;
        }
        $ossFileUrls = [];
        foreach ($savename as $sfile) {
          $sfile['url'] = str_replace('\\', '/', $sfile['url']);
          $fileD = new \Yurun\Util\YurunHttp\Http\Psr7\UploadedFile($sfile['name'], null, UPLOAD_PATH . $sfile['url']);
          $file_hash = md5_file(UPLOAD_PATH . $sfile['url']);
          $uploadResult = doFileUpload($fileD, 'FS-4829002155550872', 'FC-4830465021604083',null, $file_hash, $this->setting['dev_key']);
          if ($uploadResult['code'] == 200) {
            $ossFileUrls[] = $uploadResult['data']['url'];
          }
          unlink(UPLOAD_PATH . $sfile['url']);
        }
        if ($type == 'wangeditor') {
          $return['errno'] = 0;
          $return['data'] = [];
          foreach ($ossFileUrls as $file) {
            $return['data'][] = ['url' => $file];
          }
        } else {
          $return['code'] = 200;
          $return['data'] = $ossFileUrls;
        }
        return json($return);
      } else {
        var_dump($info);
        var_dump($file);
      }
    }
  }
  public function uploadFileWithServer()
  {
    if (request()->isPost()) {
      $file = request()->file();
      $fs_id = input('param.fs_id');
      $fc_id = input('param.fc_id');
      $save_type = input('param.save_type');
      if ($save_type == 1 || $save_type == '1') {
        $fs_id = 'FS4933086915831262';
        $fc_id = 'FC4901539840376723';
        checkIsTry($this->user['user_type']);
      }
      $savename = [];
      $result = [];
      if (!$file) {
        return Result::Error('未获取到文件');
      }
      foreach ($file as $ins) {
        $item['url'] = \think\facade\Filesystem::disk('public')->putFile('file', $ins);
        $item['name'] = $ins->getOriginalName();
        $savename[] = $item;
      }
      $uploadResult = [];
      foreach ($savename as $sfile) {
        $sfile['url'] = str_replace('\\', '/', $sfile['url']);
        $fileD = new \Yurun\Util\YurunHttp\Http\Psr7\UploadedFile($sfile['name'], null, UPLOAD_PATH . $sfile['url']);
        $file_hash = md5_file(UPLOAD_PATH . $sfile['url']);
        $uploadResult = doFileUpload($fileD, $fs_id,$fc_id,null, $file_hash, $this->setting['dev_key']);
        if ($uploadResult['code'] == 200) {
          $result[] = $uploadResult['data'];
        }
        unlink(UPLOAD_PATH . $sfile['url']);
      }
      return json(['code' => 200, 'data' =>$result, 'msg' =>'success', 'upload_result' =>$uploadResult, 'savename' => $savename]);
    }
  }
  public function uploadCrt()
  {
    header('Content-Type:application/json; charset=utf-8');
    if (request()->isPost()) {
      $file = request()->file();
      $info = validate(['application' => 'fileExt:crt'])->check($file);
      if ($info) {
        //基于框架根目录的文件路径
        $savename = [];
        foreach ($file as $ins) {
          $savename[] = \think\facade\Filesystem::disk('crt')->putFile('file', $ins);
        }
        return json(['code' => 200, 'data' => $savename[0], 'msg' => 'success']);
      } else {
        var_dump($info);
        var_dump($file);
        // 上传失败获取错误信息
      }
    }
  }
  public function deleteFileCommon()
  {
    $pic_url = input('param.pic');
    $fs_id = input('param.fs_id');
    $parseUrl = parse_url($pic_url);
    @unlink(PUBLIC_PATH . $parseUrl['path']);
    deleteFile('', $fs_id, $this->uid, null, $pic_url);
    return Result::Success('','删除成功');
  }
  /**
   * 获取验证码
   * @return void
   * @author QianLong <87498106@qq.com>
   * @date 2021-03-27 15:07:20
   * @editAuthor QianLong <87498106@qq.com>
   * @editDescription 
   * @editDate 2021-03-27 15:07:20
   */
  public function getSmsCode()
  {
    $phone = input('param.phone/s', '', 'trim');
    $type = input('param.type/s', '', 'trim');
    $ip = get_client_ip();
    if (empty($phone)) {
      return Result::Error('手机号不能为空');
    }
    if (checkphone($phone) != true) {
      return Result::Error('手机号格式不正确');
    }
    $dataVerify['token'] = input('param.token/s', '', 'trim');
    $dataVerify['authenticate'] = input('param.authenticate/s', '', 'trim');
    Verify::check($dataVerify);
    $has_phone = Manager::field('id')->where('phone', $phone)->where('id', $this->uid)->find();
    if ($type == 'change_phone_new') {
      if (!empty($has_phone)) {
        return Result::Error('该手机号已注册帐号，请更换手机号');
      }
    } else if ($type == 'change_phone_old') {
      if (empty($has_phone)) {
        return Result::Error('该手机号不正确，请确认后重试');
      }
    } else {
      if (empty($has_phone)) {
        return Result::Error('该手机号未注册帐号，请确认');
      }
    }

    if ($this->redis->ttl('sms_tj' . $ip) === -1) {
      $this->redis->del('sms_tj' . $ip);
    }
    if ($this->redis->exists('sms_tj' . $ip)) {
      $ipPhone = $this->redis->get('sms_tj' . $ip);
      if (($ipPhone > 5) && (!empty($ipPhone))) {
        return Result::Error('短信码获取频繁，请1小时后重试！');
      } else {
        $this->redis->incr('sms_tj' . $ip);
      }
    } else {
      $this->redis->set('sms_tj' . $ip, 1, 3600);
    }
    $smsCode = random_int(1000, 9999);
    $this->redis->set('smsCode:' . $phone, $smsCode, 600);
    $smsPostData['params_json'] = json_encode(['code' => $smsCode]);
    $smsPostData['st_id'] = 'ST-4820681927551383';
    $smsPostData['phone'] = $phone;
    $smsPostData['dev_key'] = $this->setting['dev_key'];
    $sendResult = doSendSms($smsPostData);
    if (isset($sendResult['code']) && $sendResult['code'] == 200) {
      return Result::Success([], '发送成功');
    } else {
      return Result::Error('发送失败，请稍后重试 [Msg:' . $sendResult['msg'] . ']');
    }
  }
  public function getSmsCodeContract()
  {
    $ip = get_client_ip();
$id = input('param.id');
    if ($this->redis->ttl('sms_tj_contract' . $ip) === -1) {
      $this->redis->del('sms_tj_contract' . $ip);
    }
    if ($this->redis->exists('sms_tj_contract' . $ip)) {
      $ipPhone = $this->redis->get('sms_tj_contract' . $ip);
      if (($ipPhone > 5) && (!empty($ipPhone))) {
        return Result::Error('短信码获取频繁，请1小时后重试！');
      } else {
        $this->redis->incr('sms_tj_contract' . $ip);
      }
    } else {
      $this->redis->set('sms_tj_contract' . $ip, 1, 3600);
    }
    $smsCode = random_int(1000, 9999);
    $contractInfo = Db::connect('mongodb')->name('contract')->field('fqs_jingban_phone')->where('_id', $id)->find();
    if (empty($contractInfo)) {
      return Result::Error('电子合同不存在或已作废');
    }
    $this->redis->set('contractSmsCode:' . $contractInfo['fqs_jingban_phone'], $smsCode, 600);
    $smsPostData['params_json'] = json_encode(['code' => $smsCode]);
    $smsPostData['st_id'] = 'ST4900638604102078';
    $smsPostData['phone'] = $contractInfo['fqs_jingban_phone'];
    $sendResult = doSendSms($smsPostData);
    contractFee($id, 0.045, '获取验证码', $this->uid);
    if (isset($sendResult['code']) && $sendResult['code'] == 200) {
      insertContractLog($this->uid, '【发起人】签署合同', $id, '获取验证码成功',1,'手机号：'. $contractInfo['fqs_jingban_phone'].'，验证码：'. $smsCode);
      return Result::Success([], '发送成功');
    } else {
      return Result::Error('发送失败，请稍后重试 [Msg:' . $sendResult['msg'] . ']');
    }
  }
}
